<template>
  <div class="employees-container">
    <div class="app-container">
      <el-card shadow="always" :body-style="{ padding: '20px' }">
        <div slot="header">
          <PageTools>
            <!-- 插入到left插槽位置 -->
            <template #left>
              <span>总记录数：{{ total }}条</span>
            </template>
            <!-- 插入到right插槽位置 -->
            <template #right>
              <el-button type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
              <el-button type="danger" size="small" @click="exportExcel">导出excel</el-button>
              <el-button v-if="checkPoints('p-emadd')" type="primary" size="small" @click="showDialog=true">新增员工</el-button>
            </template>
          </PageTools>
        </div>
        <div>
          <!-- table列表 -->
          <el-table :data="list" border :default-sort="{prop: 'workNumber'}">
            <el-table-column type="index" label="序号" />
            <el-table-column width="150px" prop="username" label="姓名" />
            <el-table-column label="员工头像">
              <template #default="{row}">
                <el-image class="round" :src="row.staffPhoto" @click="show2D(row.staffPhoto)" />
              </template>
            </el-table-column>

            <el-table-column prop="workNumber" label="工号" />
            <el-table-column prop="formOfEmployment" label="聘用形式">
              <template #default="{row}">
                {{ formatEmloyeeFN(row.formOfEmployment) }}
              </template>
            </el-table-column>
            <el-table-column prop="departmentName" label="部门" />
            <el-table-column sortable prop="timeOfEntry" label="入职时间" />
            <el-table-column label="账户状态">
              <el-switch v-model="active" />
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="280">
              <template #default="{row}">
                <el-button type="text" size="small" @click="$router.push('/employees/detail/'+row.id)">查看</el-button>
                <el-button type="text" size="small" @click="openRole(row.id)">分配角色</el-button>
                <el-button type="text" size="small" @click="delStuff(row.id)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页组件 -->
          <el-row
            type="flex"
            justify="center"
            align="middle"
            style="height: 60px"
          >
            <el-pagination layout="prev, pager, next" :total="total" :current-page="params.page" :page-size="params.size" @current-change="changePage" />
          </el-row>
        </div>
      </el-card>
    </div>
    <!-- 添加角色弹窗 -->
    <AssignRole ref="addRole" :show-role-dialog.sync="showRoleDialog" />
    <!-- 新增弹窗组件 -->
    <AddEmployee :show-dialog.sync="showDialog" />
    <el-dialog
      title="二维码"
      :visible.sync="centerDialogVisible"
      width="20%"
      center
    >
      <canvas ref="myCanvas" class="mid" />
      <span slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="centerDialogVisible = false">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getEmployeeList, delEmployeeAPI } from '@/api/employee.js'
import hireType from '@/api/constant/employees.js'
import AddEmployee from './component/add-stuff.vue'
import AssignRole from './component/assign-role.vue'
import QrCode from 'qrcode'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AssignRole
  },
  data() {
    return {
      list: [],
      params: {
        page: 1,
        size: 10
      },
      total: 0,
      active: true,
      showDialog: false,
      centerDialogVisible: false,
      currentSrc: '',
      // 控制角色弹窗
      showRoleDialog: false
    }
  },

  created () {
    this.getEmployeeLists()
  },
  methods: {
    openRole(id) {
      this.showRoleDialog = true
      this.$refs.addRole.recover(id)
    },
    show2D(src) {
      this.currentSrc = src
      console.log(src)
      this.centerDialogVisible = true
      this.$nextTick(() => {
        QrCode.toCanvas(this.$refs.myCanvas, this.currentSrc)
      })
      this.currentSrc = ''
    },
    // 导出列表
    exportExcel() {
      // 按需引入js文件，懒加载，只有触发点击事件的时候才开始加载文件
      import('@/utils/Export2Excel').then(excel => {
        const ships = {
          '手机号': 'mobile',
          '姓名': 'username',
          '入职日期': 'timeOfEntry',
          '聘用形式': 'formOfEmployment',
          '工号': 'workNumber',
          '转正日期': 'correctionTime',
          '部门': 'departmentName'
        }
        const header = Object.keys(ships)
        const data = this.transFormExcel(this.list, Object.values(ships))
        excel.export_json_to_excel({
          header,
          data,
          filename: this.filename,
          autoWidth: this.autoWidth,
          bookType: this.bookType
        })
      })
    },
    transFormExcel(list, headers) {
      const parentArray = []
      list.forEach(item => {
        const childArray = []
        for (const key in item) {
          if (headers.includes(key)) {
            // 判断，如果键值为员工雇佣类型时，对值进行转换，转换的函数已经封装好
            if (key === 'formOfEmployment') {
              childArray.push(this.formatEmloyeeFN(item[key]))
            }
          }
          childArray.push(item[key])
        }
        parentArray.push(childArray)
      })
      return parentArray
    },

    // transFormExcel(list, headers) {
    //   const parentArray = []
    //   // 遍历循环每一项，每一项的格式是
    //   list.forEach(item => {
    //     const childArray = []
    //     for (const key in item) {
    //       if (headers.includes(key)) {
    //         // 将每一项的值push进新的数组中，这里的值是item.[key]
    //         if (key === 'formOfEmployment') {
    //           childArray.push(this.formatEmloyeeFN(item[key]))
    //         } else {
    //           childArray.push(item[key])
    //         }
    //       }
    //     }
    //     parentArray.push(childArray)
    //   })
    //   return parentArray
    // },

    // ---------------
    // 获取员工列表
    async getEmployeeLists() {
      const data = await getEmployeeList(this.params)
      // console.log(data)
      this.total = data.total
      this.list = data.rows
      // console.log(this.list)
      console.log(this.list)
    },
    changePage(page) {
      this.params.page = page
      this.getEmployeeLists(this.params)
    },
    // 格式化聘用形式函数
    formatEmloyeeFN(id) {
      const map = {}
      hireType.hireType.forEach(item => {
        map[item.id] = item.value
      })
      return map[id]
    },
    // 删除员工
    delStuff(id) {
      this.$confirm('确认要删除吗？', '提示').then(async() => {
        await delEmployeeAPI(id)
        // 逻辑补充，最后一页的数据被删除时页面出错，删除所有数据页码跳转到0等问题
        const newtotal = Math.ceil((this.total - 1) / this.params.size)
        // 排除新的页码等于零的情况
        if (newtotal > 0) {
          // 重新赋值当前页码：如果当前页码大于实际页码，则赋值实际页码，相反则不变
          this.params.page = this.params.page > newtotal ? newtotal : this.params.page
        }
        // 提示
        this.$message.success('删除成功！')
        // 重新拉取数据
        this.getEmployeeLists()
      }).catch(error => {
        console.log(error)
      })
    }
  }

}
</script>

<style lang="scss" scoped>
.round{
  margin-left: 45px;
  width: 80px;
  height: 80px;
  border-radius: 50%;
}
.mid{
  margin-left: 75px;
}
</style>
